package com.qfedu.zy.utils;

import com.qfedu.zy.dao.PermissionDAO;
import com.qfedu.zy.dao.RoleDAO;
import com.qfedu.zy.dao.UserDAO;
import com.qfedu.zy.pojos.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;

import java.util.Set;

@ControllerAdvice
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private RoleDAO roleDAO;

    @Autowired
    private PermissionDAO permissionDAO;

//    public void setUserDAO(UserDAO userDAO) {
//        this.userDAO = userDAO;
//    }

    @Override
    public String getName(){
        return "myRealm01";
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获得授权用户信息
        User user = (User) principalCollection.iterator().next();
        int userId= user.getUserId();

        //2.通过user的id查询当前用户的所有角色名
        Set<String> roles = roleDAO.queryRolesByUserId(userId);

        Set<String> permissions = permissionDAO.queryPermissionByUserId(userId);

        //3.通过user的id查询当前用户的所有权限percode
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.从token中获取用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());

        String md5Pwd = new SimpleHash("MD5",password).toHex();
        //2.根据用户名查询数据库(UserDAO)
        User user = userDAO.queryUserByName(username);

        if (user == null){
            throw new UnknownAccountException("账号不存在");
        }else{
            //用户存在则验证密码
            if ( !user.getUserPwd().equals(md5Pwd)){
                throw new IncorrectCredentialsException("密码错误");
            }
        }
        return new SimpleAuthenticationInfo(user,password,getName());
    }


}
